﻿/*
 * Copyright (C) 2014 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using UnityEngine;
using System.Collections;
using System;

public class MotionDetect : MonoBehaviour
{
    private const float MotionThreshold = 0.05f;

    // time between consecutive checks
    private const float CheckInterval = 0.5f;

    // object's position at last check
    private Vector3 mLastPosition;

    // countdown to next check
    private float mCountdownToCheck = CheckInterval;

    // how many failed checks so far?
    private int mFailedChecks = 0;

    // how many failed checks are required to consider object to be at rest?
    private const int FailedChecksForRest = 3;

    // did we conclude the object is at rest?
    private bool mIsAtRest = false;

    void Start()
    {
        mLastPosition = gameObject.transform.position;
    }

    void Update()
    {
        mCountdownToCheck -= Time.deltaTime;
        if (mCountdownToCheck < 0)
        {
            mCountdownToCheck = CheckInterval;
            Check();
        }
    }

    void Check()
    {
        Vector3 delta = gameObject.transform.position - mLastPosition;
        float displacement = delta.magnitude;
        mLastPosition = gameObject.transform.position;

        if (displacement >= MotionThreshold)
        {
            // moved!
            mIsAtRest = false;
            mFailedChecks = 0;
            return;
        }

        if (mFailedChecks < FailedChecksForRest)
        {
            mFailedChecks++;
        }
        else
        {
            mIsAtRest = true;
        }
    }

    public bool IsAtRest
    {
        get { return mIsAtRest; }
    }
}